package com.cloudkinto.common.utils;

import cn.afterturn.easypoi.csv.CsvExportUtil;
import cn.afterturn.easypoi.csv.entity.CsvExportParams;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * Author Administrator
 *
 * @Des
 * @Version
 * @Date 2020/7/23
 */
public class CsvUtils {

    public static void exportCsv(CsvExportParams exportParams, Class<?> classType, List<?> data, String fileName, HttpServletResponse response) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(fileName, "UTF-8"));
            CsvExportUtil.exportCsv(exportParams, classType, data, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void exportCsv(CsvExportParams exportParams, Class<?> classType, List<?> data, String fileName, String filePathTemp) {
        File file = new File(filePathTemp + File.separator + fileName);
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        }
        CsvExportUtil.exportCsv(exportParams, classType, data, fileOutputStream);
    }
}
